axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net';
const tb = document.querySelector('#tb');
const form = document.querySelector('#bookForm');
const sx = document.querySelector('.sx');
// 封装渲染数据的函数
function renderData() {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res;
    console.log(data);
    const html = data
      .map((item) => {
        return `<tr>
            <td>${item.id}</td>
            <td>${item.bookname}</td>
            <td>${item.author}</td>
            <td>${item.publisher}</td>
            <td><a href="#"  data-id="${item.id}">删除</a></td>
          </tr>`;
      })
      .join('');
    tb.innerHTML = html;
  });
}
renderData();

// 添加
form.addEventListener('submit', function (e) {
  e.preventDefault();

  const data = serialize(form, { hash: true });
  axios.post('/api/addbook', data).then(({ data: res }) => {

    alert(res.msg);
    if (res.status !== 201) return;
    console.log(res);
    renderData();
    form.reset();
  });
});

// 删除
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id;
    axios
      .get('/api/delbook', {
        params: {
          id,
        },
      })
      .then(({ data: res }) => {
        console.log(res);
        renderData();
      });
  }
});

// 筛选
sx.addEventListener('click', function () {
  const newData = serialize(form, { hash: false });
  axios.get('/api/getbooks?' + newData).then(({ data: res }) => {
    if (!newData) return alert('请选择要筛选的内容');

    const { data } = res;
    const html = data
      .map((item) => {
        return `<tr>
            <td>${item.id}</td>
            <td>${item.bookname}</td>
            <td>${item.author}</td>
            <td>${item.publisher}</td>
            <td><a href="#"  data-id="${item.id}">删除</a></td>
          </tr>`;
      })
      .join('');
    tb.innerHTML = html;
    form.reset()
  });
});
